class SportsController < ApplicationController
  # 显示 sport 
  def show
    flash[:notice]= params[:notice] if params[:notice] and !flash[:notice]
    flash[:error]= params[:error] if params[:error] and !flash[:error]
    @sport = Sport.find params[:id]
    @league = League.find_by_id(params[:league_id])
    # exclude beted matches
    @matches = @sport.matches.played(false)
    @matches = @matches.scoped(:conditions=>["#{Match.table_name}.begin_at > ?",Time.now.to_formatted_s(:db)]) # filter expired matches.

    @matches = case params[:order_by]
    when "comment_count"
      limit = SETTINGS["sport.filter.popular.limit"] || 6
      @matches = @matches.scoped(:order=>"#{Match.table_name}.comment_count DESC")
      @matches.all :limit=>limit
    when "most_bets"
      # 朋友中最多bets的match
      limit = SETTINGS["sport.filter.most_bets.limit"] || 6
      @matches = @matches.scoped(:order=>"#{Match.table_name}.bets_count desc",:conditions=>["#{Bet.table_name}.user_id in (?)",current_user.friend_ids],:joins=>:bets)
      @matches.all :limit=>limit
    else
      # normal
      @matches = @matches.scoped(:conditions=>{:league_id=>@league.id}) if @league
      @matches.scoped(:order=>"#{Match.table_name}.begin_at ASC,#{Match.table_name}.id ASC")
      @matches = @matches.paginate :page=>params[:page],
        :conditions=>["#{Match.table_name}.id NOT IN (SELECT match_id from #{Bet.table_name} WHERE #{Bet.table_name}.user_id = '#{current_user.id}')",current_user.match_ids]

    end


  end
end
